import config from 'configs/config.js'
const request = (
    // uview Toast的指向this
    that = {},
    // 请求地址和请求方式
    urlType = {
        url: '',
        type: 'GET',
    },
    // 请求参数
    data = {}, 
    // 头部信息
    header = {
        "Content-Type": "application/json",
        Authorization: urlType.isAuthorization == false ? '' : uni.getStorageSync("Authorization")
    }
) => {
    return new Promise((resolve, reject) => {
        // const baseUrl = uni.getStorageSync("baseUrl") ? uni.getStorageSync("baseUrl") : 'http://220.171.59.122:8083/'
        uni.request({
            method: urlType.type,
            // url: baseUrl + urlType.url,
            url: config.baseUrl + urlType.url,
            data: data,
            header: header,
            dataType: 'json',
        }).then((response) => {
            uni.hideLoading()
            let [ error,res ] = response
            // console.log('请求成功',res,error)
            if (res.statusCode == 200 ){
                if( res.data.code == 200 ){
                    if (urlType.paging){
                        resolve( res.data )
                    }else{
                        resolve(res.data.data ? res.data.data : res.data)
                    }
                } else if (res.data.code == 401) {
                    uni.$u.toast('登陆过期,即将重新登陆', 1500)
                    setTimeout(() => {
                        uni.reLaunch({ url: '/pages/login/login' })
                    }, 1500);
                }else {
                    uni.$u.toast(res.data.msg)
                }
            }else{
                uni.$u.toast(res ? res.errMsg : error.errMsg)
            }
        }).catch(error => {
            uni.hideLoading()
            let [err, res] = error
            // console.log('请求失败', res, err)
            reject(err)
        })
    });
}
export default request